import { rangeHandler } from "./range";
import {
  hoverBarPosition,
  isFocusNoteEditor,
  selectedText,
  hoverBarRef,
} from "./state";
import { TextStyleModifier } from "./textStyleModifier";
import { updateTextContent } from "./utils";
import { useNoteStore } from "@/store/modules/note";
const noteStore = useNoteStore();

let isMouseEnterNoteEditor = false;
function onNoteEditorMouseEnter() {
  isMouseEnterNoteEditor = true;
}

function onNoteEditorMouseOut() {
  isMouseEnterNoteEditor = false;
}

export const noteEditorEvents = {
  onNoteEditorMouseEnter,
  onNoteEditorMouseOut,
};

function handleSpanMouseOut() {
  // 如果鼠标移入批注框，则不隐藏批注框
  setTimeout(() => {
    if (!isMouseEnterNoteEditor) {
      noteStore.isShowedNote = false;
    }
  }, 500);
}

function handleFunctionsPosition(event: MouseEvent) {
  hoverBarPosition.x = event.pageX - 160;
  hoverBarPosition.y = event.pageY - 80;
}

// 以下为事件
function onMouseMove(event: MouseEvent) {
  const target = event.target as Element;
  if (!noteStore.shouldShowNote(target)) return;

  const axis = getElementBottomCenterAxis(target.id)!;

  noteStore.changeCurrentNote(target.id);
  noteStore.showNote(target.id, axis);
}

function onMouseOut(event: MouseEvent) {
  if (isFocusNoteEditor.value) return;

  const target = event.target as Element;
  if (target.nodeName === "SPAN") {
    handleSpanMouseOut();
  }
}

let timer: undefined | number;
function onMouseDown(event: MouseEvent) {
  console.log("按下");
  noteStore.rangeAxis.startX = event.pageX;
  noteStore.rangeAxis.startY = event.pageY;
  rangeHandler.saveCursorPosition();
  rangeHandler.saveAnchorOffset();
}

function onCompositionend(event: Event) {
  const target = event.target as HTMLElement;
  updateTextContent(target);
}

function onTotalContentInput(event: Event) {
  if ((event as InputEvent).isComposing) return;
  const target = event.target as HTMLElement;
  updateTextContent(target);
}

function onSelectedTextMouseUp(event: MouseEvent) {
  rangeHandler.saveAnchorOffset();
  noteStore.rangeAxis.endX = event.pageX;
  noteStore.rangeAxis.endY = event.pageY;
  selectedText.value = TextStyleModifier.getSelectedTextContent();
  const range = getSelection()?.getRangeAt(0)!;

  // 光标开始与结束位置重合，表明未选中任何内容
  if (range.collapsed) return;
  if (selectedText.value) {
    //延迟开启hoverBar，避免mouseup事件后的document.click触发又将hoverBar关闭。
    setTimeout(() => {
      hoverBarRef.value?.openHoverBar();
      handleFunctionsPosition(event);
    });
  }
}

export const editableEvents = {
  onMouseMove,
  onMouseOut,
  onMouseDown,
  onCompositionend,
  onTotalContentInput,
  onSelectedTextMouseUp,
};
